#!/bin/bash
# Copyright (c) 2021 maminjie <maminjie1@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

usage() {
    echo "Usage: script subcmd [args]"
    echo ""
    echo "using to install/localinstall/remove/update packages"
    echo ""
    echo "Note: the names of packages are obtained from local *.rpm"
    echo ""
    echo "subcmd:"
    echo "      install [--repo xxx  ...]   install the packages from yumrepo"
    echo "      localinstall                install the local rpm packages"
    echo "      update                      update the packages"
    echo "      downgrade                   downgrade the packages"
    echo "      remove                      remove the pacages"
    echo ""
}

get_binnames() {
    rpms=$(ls *.rpm)
    pkgs=""
    for r in $rpms; do
        name=$(rpm -qi $r 2>/dev/null | grep "Name" | head -n1 | awk -F : '{print $2}' | sed 's/\s\+//g')
        if [ -z "$pkgs" ]; then
            pkgs=$name
        else
            pkgs="$pkgs $name"
        fi
    done
    echo "$pkgs"
}

yum_install() {
    pkgs=$(get_binnames)
    if [ -n "$pkgs" ]; then
	    yum install $pkgs $@
    fi
}

yum_localinstall() {
    pkgs=$(get_binnames)
    echo "yum install $pkgs"
	yum install *.rpm
}

yum_update() {
    pkgs=$(get_binnames)
    if [ -n "$pkgs" ]; then
	    yum update $pkgs
    fi
}

yum_downgrade() {
    pkgs=$(get_binnames)
    if [ -n "$pkgs" ]; then
	    yum downgrade $pkgs
    fi
}

yum_remove() {
    pkgs=$(get_binnames)
    if [ -n "$pkgs" ]; then
	    yum remove $pkgs
    fi
}

main() {
    local subcmd=$1

    if [ $# -gt 0 ]; then
        shift
    fi

    case $subcmd in
        "install")
            yum_install "$@"
            ;;
        "localinstall")
            yum_localinstall "$@"
            ;;
        "update")
            yum_update "$@"
            ;;
        "downgrade")
            yum_downgrade "$@"
            ;;
        "remove")
            yum_remove "$@"
            ;;
        *)
            usage
            ;;
    esac

}

main "$@"

